<template>
  <div class="goods-relevant">
    <div class="header">
      <i class="icon"></i>
      <span class="title">{{ goodsId.length !== 0 ? '同类商品推荐' : '猜你喜欢' }}</span>
    </div>
    <!-- 此处使用改造后的xtx-carousel.vue -->
    <XtxCarousel :sliders="sliders"></XtxCarousel>
  </div>
</template>

<script>
import API from '@/api/goods'
import { ref } from 'vue'

export default {
  name: 'GoodsRelevant',
  props: {
    goodsId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    // 最终需要的数据是 sliders 提供给轮播图使用
    // 数据结构: slider = [[4张img], [4张img], [4张img], [4张img]]
    const sliders = ref([])

    API.getRelevantGoods({ id: props.goodsId })
      .then(res => {
        // res.result 商品列表, 数据结构 [16个]
        // 将data.result数据赋值给sliders数据, 保证数据结构正确
        const pageSize = 4
        const pageCount = Math.ceil(res.result.length / pageSize)

        for (let i = 0; i < pageCount; i++) {
          // arr.slice(begin, end) --> [begin, end)
          sliders.value.push(res.result.slice(pageSize * i, pageSize * (i + 1)))
        }

        // let count = 1
        // let arr = []
        // for (let i = 0; i < res.result.length; i++) {
        //   arr.push(res.result[i])
        //   count++
        //   if (count > pageSize) {
        //     count = 1
        //     sliders.value.push(arr)
        //     arr = []
        //   }
        // }
      })

    return {
      sliders
    }
  }

}
</script>

<style lang="less" scoped>

.goods-relevant {
  min-height: 460px;
  background-color: #fff;
  margin-top: 20px;

  .header {
    padding: 0 20px;
    height: 80px;
    line-height: 80px;

    // 画出一个图标
    .icon {
      display: inline-block;
      width: 16px;
      height: 16px;
      position: relative;

      border-top: 4px solid @xtxColor;
      border-right: 4px solid @xtxColor;
      transform: rotate(45deg);

      &::before {
        content: '';
        width: 10px;
        height: 10px;
        position: absolute;
        top: 2px;
        left: 0;
        background-color: lighten(@xtxColor, 40%);
      }
    }

    .title {
      font-size: 20px;
      margin-left: 10px;
    }
  }

  // vue3.0写法
  //  ::v-deep usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead.
  :deep(.xtx-carousel) {
    height: 380px;

    .carousel-indicator {
      bottom: 30px;

      span {
        &.active {
          background: @xtxColor;
        }
      }
    }

    .carousel-btn {
      top: 110px;
      opacity: 1;
      color: #ddd;
      background-color: rgba(0, 0, 0, 0);
      transform: none;

      .iconfont {
        font-size: 30px;
      }
    }
  }
}
</style>
